package com.hhf.rpa.engine.service.impl;

import com.hhf.rpa.engine.model.ScriptExecConfigurer;
import com.hhf.rpa.engine.service.ScriptExecutor;
import com.hhf.rpa.glue.SpringBeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

@Service
public class SimpleScriptExecutor implements ScriptExecutor {

    public Object execScript(ScriptExecConfigurer configurer) throws ClassNotFoundException {
        Class<?> clazz = Class.forName(configurer.getClassName());
        String className = lowerFirstCapse(clazz.getSimpleName());
        Object bean = SpringBeanUtils.getBean(className);
        Class<?>[] paramTypeArray = new Class[0];
        paramTypeArray[0] = String.class;
        Method method = ReflectionUtils.findMethod(bean.getClass(), configurer.getMethod(), paramTypeArray);
        Assert.notNull(method, bean.getClass() + "#" + configurer.getMethod() + " not exists");
        String[] paramArray = new String[]{configurer.getParams()};
        System.setProperty("java.awt.headless", "false");
        return ReflectionUtils.invokeMethod(method, bean, paramArray);
    }

    /**
     * 转换首字母小写
     *
     * @param str
     * @return
     */
    private static String lowerFirstCapse(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
